package cc.uncarbon.module.custom.service;

import cc.uncarbon.framework.core.constant.HelioConstant;
import cc.uncarbon.framework.core.enums.EnabledStatusEnum;
import cc.uncarbon.framework.core.exception.BusinessException;
import cc.uncarbon.framework.core.page.PageParam;
import com.yanrumiao.entity.PageResult;
import cc.uncarbon.module.custom.entity.StoreEntity;
import cc.uncarbon.module.custom.mapper.StoreMapper;
import cc.uncarbon.module.custom.model.request.AdminStoreInsertOrUpdateDTO;
import cc.uncarbon.module.custom.model.request.AdminStoreListDTO;
import cc.uncarbon.module.custom.model.response.StoreBO;
import cc.uncarbon.module.custom.model.response.StoreListBO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;


/**
 * 商户
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class StoreService {

    private final StoreMapper storeMapper;


    /**
     * 后台管理-分页列表
     */
    public PageResult<StoreBO> adminList(PageParam pageParam, AdminStoreListDTO dto) {
        Page<StoreEntity> entityPage = storeMapper.selectPage(
                new Page<>(pageParam.getPageNum(), pageParam.getPageSize()),
                new QueryWrapper<StoreEntity>()
                        .lambda()
                        // 商户名称
                        .like(CharSequenceUtil.isNotBlank(dto.getName()), StoreEntity::getName, CharSequenceUtil.cleanBlank(dto.getName()))
                        // 商户地址
                        .like(CharSequenceUtil.isNotBlank(dto.getAddress()), StoreEntity::getAddress, CharSequenceUtil.cleanBlank(dto.getAddress()))
                        // 商户Logo图片链接
                        .like(CharSequenceUtil.isNotBlank(dto.getLogo()), StoreEntity::getLogo, CharSequenceUtil.cleanBlank(dto.getLogo()))
                        // 法人姓名
                        .like(CharSequenceUtil.isNotBlank(dto.getLegalPersonName()), StoreEntity::getLegalPersonName, CharSequenceUtil.cleanBlank(dto.getLegalPersonName()))
                        // 法人联系电话
                        .like(CharSequenceUtil.isNotBlank(dto.getLegalPersonPhone()), StoreEntity::getLegalPersonPhone, CharSequenceUtil.cleanBlank(dto.getLegalPersonPhone()))
                        // 身份证正面图片链接
                        .like(CharSequenceUtil.isNotBlank(dto.getIdCardFront()), StoreEntity::getIdCardFront, CharSequenceUtil.cleanBlank(dto.getIdCardFront()))
                        // 身份证反面图片链接
                        .like(CharSequenceUtil.isNotBlank(dto.getIdCardBack()), StoreEntity::getIdCardBack, CharSequenceUtil.cleanBlank(dto.getIdCardBack()))
                        // 排序序号
                        .eq(ObjectUtil.isNotNull(dto.getSortOrder()), StoreEntity::getSortOrder, dto.getSortOrder())
                        // 状态
                        .eq(ObjectUtil.isNotNull(dto.getStatus()), StoreEntity::getStatus, dto.getStatus())
                        // 时间区间
                        .between(ObjectUtil.isNotNull(dto.getBeginAt()) && ObjectUtil.isNotNull(dto.getEndAt()), StoreEntity::getCreatedAt, dto.getBeginAt(), dto.getEndAt())
                        // 排序
                        .orderByDesc(StoreEntity::getCreatedAt)
        );

        return this.entityPage2BOPage(entityPage);
    }

    /**
     * 根据 ID 取详情
     *
     * @param id 主键ID
     * @return null or BO
     */
    public StoreBO getOneById(Long id) {
        return this.getOneById(id, false);
    }

    /**
     * 根据 ID 取详情
     *
     * @param id               主键ID
     * @param throwIfInvalidId 是否在 ID 无效时抛出异常
     * @return null or BO
     */
    public StoreBO getOneById(Long id, boolean throwIfInvalidId) throws BusinessException {
        StoreEntity entity = storeMapper.selectById(id);
        if (throwIfInvalidId && entity == null) {
            throw new BusinessException(400, "无效商户ID");
        }

        return this.entity2BO(entity);
    }

    /**
     * 后台管理-新增
     */
    @Transactional(rollbackFor = Exception.class)
    public Long adminInsert(AdminStoreInsertOrUpdateDTO dto) {
        log.info("[后台管理-商户-新增] >> DTO={}", dto);
        this.checkExistence(dto);

        dto.setId(null);
        StoreEntity entity = new StoreEntity();
        BeanUtil.copyProperties(dto, entity);

        storeMapper.insert(entity);

        return entity.getId();
    }

    /**
     * 后台管理-编辑
     */
    @Transactional(rollbackFor = Exception.class)
    public void adminUpdate(AdminStoreInsertOrUpdateDTO dto) {
        log.info("[后台管理-商户-编辑] >> DTO={}", dto);
        this.checkExistence(dto);

        StoreEntity entity = new StoreEntity();
        BeanUtil.copyProperties(dto, entity);

        storeMapper.updateById(entity);
    }

    /**
     * 后台管理-删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void adminDelete(Collection<Long> ids) {
        log.info("[后台管理-商户-删除] >> ids={}", ids);
        storeMapper.deleteBatchIds(ids);
    }


    /*
    ----------------------------------------------------------------
                        私有方法 private methods
    ----------------------------------------------------------------
     */

    /**
     * 实体转 BO
     *
     * @param entity 实体
     * @return BO
     */
    private StoreBO entity2BO(StoreEntity entity) {
        if (entity == null) {
            return null;
        }

        StoreBO bo = new StoreBO();
        BeanUtil.copyProperties(entity, bo);

        // 可以在此处为BO填充字段

        return bo;
    }

    /**
     * 实体 List 转 BO List
     *
     * @param entityList 实体 List
     * @return BO List
     */
    private List<StoreBO> entityList2BOs(List<StoreEntity> entityList) {
        if (CollUtil.isEmpty(entityList)) {
            return Collections.emptyList();
        }

        // 深拷贝
        List<StoreBO> ret = new ArrayList<>(entityList.size());
        entityList.forEach(
                entity -> ret.add(this.entity2BO(entity))
        );

        return ret;
    }

    /**
     * 实体分页转 BO 分页
     *
     * @param entityPage 实体分页
     * @return BO 分页
     */
    private PageResult<StoreBO> entityPage2BOPage(Page<StoreEntity> entityPage) {
        return new PageResult<StoreBO>()
                .setCurrent((int) entityPage.getCurrent())
                .setSize((int) entityPage.getSize())
                .setTotal((int) entityPage.getTotal())
                .setRecords(this.entityList2BOs(entityPage.getRecords()));
    }

    /**
     * 检查是否已存在同名数据
     *
     * @param dto DTO
     */
    private void checkExistence(AdminStoreInsertOrUpdateDTO dto) {
        /*
        可以根据自己业务需要，解禁这段代码，修改判断条件和文案

        StoreEntity existingEntity = storeMapper.selectOne(
                new QueryWrapper<StoreEntity>()
                        .lambda()
                        .select(StoreEntity::getId)
                        .eq(StoreEntity::getTitle, dto.getTitle())
                        .last(HelioConstant.CRUD.SQL_LIMIT_1)
        );

        if (existingEntity != null && !existingEntity.getId().equals(dto.getId())) {
            throw new BusinessException(400, "已存在相同商户，请重新输入");
        }
        */
    }

    public List<StoreListBO> getStroeList() {
        List<StoreEntity> entityList = storeMapper.selectList(new QueryWrapper<StoreEntity>()
                .lambda()
                .eq(StoreEntity::getStatus, EnabledStatusEnum.ENABLED));
        ArrayList<StoreListBO> bos = new ArrayList<>(entityList.size());
        entityList.forEach(entity -> {
            StoreListBO bo = new StoreListBO();
            BeanUtil.copyProperties(entity, bo);
            bos.add(bo);
        });
        return bos;
    }
}
